package com.yupi.springbootinit.controller;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.mapper.CommentMapper;
import com.yupi.springbootinit.model.dto.comment.CommentDelRequest;
import com.yupi.springbootinit.model.entity.Comment;
import com.yupi.springbootinit.model.entity.CommentRq;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.vo.CommentVO;
import com.yupi.springbootinit.service.CommentService;
import com.yupi.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.List;

@RestController
@RequestMapping("/comment")
@Slf4j
public class CommentController {

    @Resource
    private CommentService commentService;

    @Resource
    private UserService userService;

    @Resource
    private CommentMapper commentMapper;

    @GetMapping("/getComment")
    public BaseResponse<List<CommentVO>> getComment(@RequestParam Long postId) {
        return ResultUtils.success(commentService.getComment(postId));
    }


    @PostMapping("/addComment")
    public BaseResponse<Long> addComment(@RequestParam(value = "content",required = true) String content, @RequestParam(value = "postId") Long postId, @RequestParam(value = "anon", defaultValue = "0") Integer anon, @RequestParam(required = false,value = "files") List<MultipartFile> files, HttpServletRequest request) {

//        if (commentAddRequest==null){
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
        Comment comment = new Comment();
        comment.setContent(content);
        comment.setPostId(postId);
        comment.setAnon(anon);

        commentService.validComment(comment,true);//add为true表示参不能为空

        User loginUser = userService.getLoginUser(request);
        if(loginUser.getIsAuth()==0){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"请先实名认证再发帖哦~");
        }
        if (loginUser.getUserPoints()<=0){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"积分不足");
        }

        comment.setUserId(loginUser.getId());
        if (comment.getAnon()==1){
            comment.setAnon_name(loginUser.getAnon_name());
        }

        if (files != null){
            List<String> imgpath = commentService.uploadImage(files);

            comment.setImgpath(JSONUtil.toJsonStr(imgpath));
        }
        boolean result = commentService.save(comment);
        if (!result) {
            return ResultUtils.error(ErrorCode.OPERATION_ERROR); // 返回错误信息而不是抛出异常
        }
        boolean reduceOnePoint = userService.reduceOnePoint(loginUser);
        ThrowUtils.throwIf(!reduceOnePoint,ErrorCode.SYSTEM_ERROR);
        long newCommetId = comment.getId();
        return ResultUtils.success(newCommetId);
    }

    @PostMapping("/deleteComment")
    public BaseResponse<Boolean> deleteComment(@RequestBody CommentDelRequest commentDelRequest, HttpServletRequest request) {
        if (commentDelRequest == null || commentDelRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = commentDelRequest.getId();
        // 判断是否存在
        Comment oldComment = commentService.getById(id);
        ThrowUtils.throwIf(oldComment == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldComment.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = commentService.removeById(id);
        return ResultUtils.success(b);
    }

    @GetMapping("/getCommentByLoginUser")
    public BaseResponse<List<Comment>> getCommentByLoginUser(HttpServletRequest request) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        User user = userService.getLoginUser(request);
        Long userId = user.getId();
        queryWrapper.eq("userId",userId);
        queryWrapper.eq("isDelete","0");
        queryWrapper.orderByDesc("createTime");
        List<Comment> commentList = commentMapper.selectList(queryWrapper);

        return ResultUtils.success(commentList);
    }
}
